
<script setup>
import { useUserStore,usePartnerStore } from '@/stores/index.js'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox  } from 'element-plus'
import { Close } from '@element-plus/icons-vue';
import { onMounted ,ref} from 'vue'
import request from '@/utils/request.js'

const userStore = useUserStore()
const partnerStore = usePartnerStore()
const router = useRouter()

//用ref定义动态变量储存用户信息
const userCompleteInfo = ref({
  student_id: '',       // 学号（默认空字符串）
  major: '',            // 专业
  grade: '',            // 年级
  intro: '',            // 简介
  study_time: '',       // 学习时间
  study_style: '',      // 学习风格
  communication_frequency: '', // 沟通频率
  selected_course_names: [] ,// 已选课程（默认空数组）
  nickname: '',         // 昵称
  avatar: ''            // 头像
});
// 数字年级 -> 中文年级的映射关系
const gradeMap = {
  1: '大一',
  2: '大二',
  3: '大三'
};
let collectedQuestions = ref([]);

// 退出登录
const handleLogout = () => {
  // userStore.removeToken()
  //提醒用户是否退出登录
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.removeToken()
    ElMessage.success('退出登录成功')
    router.push('/login')
  }).catch(() => {
    ElMessage.info('已取消退出登录')
  })
}
//获取学生信息
const getUserCompleteInfo = async () => {
  //先获取userId和student_id
  const res = await request.get('/getUserCompleteInfo',
    {
      params: {
        userId: userStore.userId,
        student_id: userStore.student_id
      }
    },
    { withCredentials: true }
  )
  //把grade
  userCompleteInfo.value = res.data
  console.log(userCompleteInfo.value)
}

const groups = ref([]);
//得到小组
const getUserGroups = async () => {
  const res = await request.get('/getUserGroups',
    { params: { userId: userStore.userId } },
  )
  groups.value = res.data;
}
//退出小组
const quitGroup = async (groupId) => {
  //提示用户是否退出小组
  ElMessageBox.confirm('确定要退出小组吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await request.post('/quitGroup',
      {
        groupId: groupId,
        userId: userStore.userId
      },
    )
    if (res.status === 200) {
      getUserGroups()
      ElMessage.success('已成功退出小组')
    }
  })
}
//删除伙伴
const deletePartner= async(partnerId)=>{
  ElMessageBox.confirm('确定要删除该伙伴吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await request.post('/deletePartner',
      {
        partnerId: partnerId,
        userId: userStore.userId
      },
    )
    if (res.status === 200) {
      partnerStore.removePartner(partnerId)
      partnerStore.fetchPartners(userStore.userId)
      ElMessage.success('已成功删除伙伴')
    }})
}
//修改信息
const modifyInformation=()=>{
router.push({
  path: '/user/finish',
  query: {
    mode: "修改信息"
  }
});
}
//获取已收藏的问题
const getQuestions = async () => {
  const res=await request.get('/getCollectQuestions',
    {
      params: {
        userId: userStore.userId,
      }
    },
    { withCredentials: true }
  )
    collectedQuestions.value = res.data.collectedQuestions
    console.log(collectedQuestions.value)
};
const formatTime = (isoTime) => {
  if (!isoTime) return '';
  const date = new Date(isoTime);
  // 格式：YYYY-MM-DD HH:MM:SS
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')} ${date.getHours().toString().padStart(2,'0')}:${date.getMinutes().toString().padStart(2,'0')}:${date.getSeconds().toString().padStart(2,'0')}`;
};
const goQuestionDetail=(questionId)=> {
  router.push({
    path: '/partner/QuestionDetail',
    query: {
      questionId: questionId,
    },
  });
}
onMounted(() => {
  getUserCompleteInfo()
  getUserGroups()
  getQuestions()
})

</script>

<template>
  <div class="personal-center">
    <!-- 绿色风格头部 -->
    <header class="green-header">
      <div class="header-content">
        <div class="logo">
          <span class="title">个人中心</span>
        </div>
        <div class="user-info">
          <img
            :src="userCompleteInfo.avatar"
            alt="用户头像"
            class="avatar"
          >
          <div class="user-name">{{ userCompleteInfo.nickname }}</div>
          <el-button
            type="primary"
            class="logout-btn"
            @click="handleLogout"
          >
            <i class="el-icon-switch-button"></i>退出登录
          </el-button>
           <el-button
            type="primary"
            class="logout-btn"
            @click="modifyInformation()"
          >
            <i class="el-icon-switch-button"></i>修改信息
          </el-button>
        </div>
      </div>
    </header>

    <!-- 主体内容区 -->
    <div class="main-container">

      <main class="content">
        <!-- 个人资料卡片 -->
        <el-card class="info-card">
          <div class="card-header">
            <h3>个人资料</h3>
          </div>
          <div class="card-body">
            <!-- 个人资料内容（在此填充） -->
            <div class="info-item">
              <span class="label">昵称：</span>
              <span class="value">{{ userCompleteInfo.nickname }}</span>
            </div>
            <div class="info-item">
              <span class="label">学号：</span>
              <span class="value">{{ userCompleteInfo.student_id }}</span>
            </div>
            <div class="info-item">
              <span class="label">专业：</span>
              <span class="value">{{ userCompleteInfo.major }}</span>
            </div>
            <div class="info-item">
              <span class="label">年级：</span>
              <span class="value">{{ gradeMap[userCompleteInfo.grade] }}</span>
            </div>
            <div class="info-item">
              <span class="label">个人简介：</span>
              <span class="value">{{ userCompleteInfo.intro }}</span>
            </div>
          </div>
        </el-card>
        <el-card class="info-card" v-if="collectedQuestions.length > 0">
          <div class="card-header">
            <h3>我的收藏问题</h3>
          </div>
        <div class="card-body">
        <div class="question-list">
          <!-- 循环渲染每条收藏问题 -->
          <div class="question-item" v-for="(question, index) in collectedQuestions" :key="question.id">
            <!-- 问题标题 -->
            <div class="question-title">
              <span class="title-text" @click="goQuestionDetail(question.id)">{{ index + 1 }}. {{ question.title }}</span>
            </div>
            <!-- 问题详情（标签、时间、统计） -->
            <div class="question-meta">
              <!-- 标签 -->
              <div class="tags">
                <span class="tag" v-for="(tag, tIdx) in question.tags" :key="tIdx">{{ tag }}</span>
              </div>
              <!-- 时间与统计 -->
              <div class="meta-info">
                <span>收藏时间：{{ formatTime(question.collectedAt) }}  </span>
                <span>提问时间：{{ formatTime(question.questionCreatedAt) }}  </span>
                <span>回答数：{{ question.answerCount }} </span>
                <span>收藏数：{{ question.collectCount }} </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 新增：无收藏问题时的提示 -->
    <el-card class="info-card" v-else-if="collectedQuestions.length === 0 && collectedQuestions !== undefined">
      <div class="card-header">
        <h3>我的收藏问题</h3>
      </div>
      <div class="card-body no-collection">
        来看看你收藏的问题吧！快去提问或搜索感兴趣的内容，然后收藏起来。
      </div>
    </el-card>
         <!-- 学习偏好卡片 -->
        <el-card class="info-card">
          <div class="card-header">
            <h3>学习偏好</h3>
          </div>
          <div class="card-body">
            <!-- 学习偏好内容（在此填充） -->
            <div class="preference-item">
              <span class="label">学习时间：</span>
              <span class="value">{{ userCompleteInfo.study_time }}</span>
            </div>
            <div class="preference-item">
              <span class="label">学习方式：</span>
              <span class="value">{{ userCompleteInfo.study_style }}</span>
            </div>
            <div class="preference-item">
              <span class="label">沟通频率：</span>
              <span class="value">{{ userCompleteInfo.communication_frequency }}</span>
            </div>
          </div>
        </el-card>


        <!-- 已选课程卡片 -->
        <el-card class="info-card">
          <div class="card-header">
            <h3>已选课程</h3>
          </div>
          <div class="card-body">
            <!-- 已选课程内容（在此填充） -->
            <div class="course-list">
              <!-- 课程项示例 -->
              <div class="course-item" v-for="(course, index) in userCompleteInfo.selected_course_names"
               :key="index">{{ course }}</div>
            </div>
            <div v-if="userCompleteInfo.selected_course_names.length === 0" class="no-course">
              暂无已选课程
            </div>
          </div>
        </el-card>

        <!-- 已经加入的小组 -->
        <el-card class="info-card">
          <div class="card-header">
            <h3>已加入小组</h3>
          </div>
          <div class="card-body">
            <!-- 已选课程内容（在此填充） -->
            <div class="course-list">
              <!-- 课程项示例 -->
              <div class="course-item" v-for="group in groups"
               :key="group.groupId">
               {{ group.groupName }}
                 <el-icon
                    class="quit-icon"
                    @click="quitGroup(group.groupId)"
                    title="退出小组"
                  >
                    <Close />
                  </el-icon>
               </div>
            </div>
            <div v-if="groups.length === 0" class="no-course">
              暂无加入的小组
            </div>
          </div>
        </el-card>

        <!-- 已经添加的伙伴 -->
        <el-card class="info-card">
          <div class="card-header">
            <h3>已添加伙伴</h3>
          </div>
          <div class="card-body">
            <div class="course-list">
              <div class="course-item" v-for="partner in partnerStore.partners"
               :key="partner.id">
               {{ partner.nickname }}
                 <el-icon
                    class="quit-icon"
                    @click="deletePartner(partner.partnerId)"
                    title="删除伙伴"
                  >
                    <Close />
                  </el-icon>
               </div>
            </div>
            <div v-if="partnerStore.partners.length === 0" class="no-course">
              暂无加入的伙伴
            </div>
          </div>
        </el-card>
      </main>
    </div>
  </div>
</template>


<style scoped>
/* 绿色头部样式 */
.green-header {
  background-color: #22c55e;
  color: white;
  padding: 0 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  height: 70px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logo .el-icon-user-circle {
  font-size: 24px;
}

.title {
  font-size: 18px;
  font-weight: 600;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.user-name {
  font-weight: 500;
}

.logout-btn
.logout-btn1{
  color: white;
  padding: 5px 10px;
}

.logout-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}


/* 主体内容样式 */
.main-container {
  display: flex;
  min-height: calc(100vh - 70px);
}

.sidebar {
  width: 220px;
  border-right: 1px solid #e5e7eb;
}

.sidebar-menu {
  border-right: none;
  height: 100%;
}

.content {
  flex: 1;
  padding: 30px;
  background-color: #f9fafb;
}

/* 卡片样式 */
.info-card {
  margin-bottom: 20px;
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f1f5f9;
}

.card-header h3 {
  font-size: 16px;
  color: #1e293b;
  margin: 0;
}

.edit-btn {
  background-color: #22c55e;
  border-color: #22c55e;
}

.edit-btn:hover {
  background-color: #16a34a;
  border-color: #16a34a;
}

.card-body {
  padding: 10px 0;
}

/* 信息项样式 */
.info-item, .preference-item {
  display: flex;
  margin-bottom: 15px;
  line-height: 1.5;
}

.label {
  width: 100px;
  color: #64748b;
  font-weight: 500;
}

.value {
  flex: 1;
  color: #1e293b;
}

/* 课程列表样式 */
.course-list {
  display: flex;
  flex-wrap: wrap; /* 允许换行，避免横向溢出 */
  gap: 8px; /* 小组项之间的间距，优化布局 */
}

.course-item {
  background-color: #ecfdf5;
  color: #065f46;
  padding: 6px 30px; /* 修复1：右侧padding从12px改为30px，给叉号留空间 */
  border-radius: 20px;
  font-size: 14px;
  display: flex;
  align-items: center;
  position: relative; /* 修复2：添加相对定位，让叉号相对于小组项定位 */
  margin-right: 8px; /* 可选：增加项之间的间距，避免拥挤 */
  margin-bottom: 8px; /* 可选：换行时的上下间距 */
}

.quit-icon {
  position: absolute;
  right: 10px; /* 相对于父元素右侧10px */
  top: 50%;
  transform: translateY(-50%);
  color: #c0c4cc;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s;
}

.quit-icon:hover {
  color: #f56c6c;
}
.question-list {
  margin-top: 10px;
}
.question-item {
  padding: 12px 0;
  border-bottom: 1px dashed #f1f5f9;
}
.question-item:last-child {
  border-bottom: none;
}
.question-title {
  margin-bottom: 8px;
}
.title-text {
  font-size: 15px;
  color: #2563eb;
  cursor: pointer;
}
.title-text:hover {
  text-decoration: underline;
}
.question-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 13px;
  color: #64748b;
}
.tags {
  display: flex;
  gap: 8px;
}
.tag {
  background-color: #dbeafe;
  color: #3b82f6;
  padding: 2px 8px;
  border-radius: 4px;
}
.no-collection {
  text-align: center;
  padding: 30px 0;
  color: #94a3b8;
  font-size: 14px;
}
</style>
